﻿using System;
using System.Data.Odbc;
using System.Dynamic;
using System.Linq;
using System.Windows.Forms;
using EzDesk.Core.Data;
using EzDesk.Core.Model;
using EzDesk.DevHelper.DebugLibrary;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Generic;
using Enumerable = System.Linq.Enumerable;

namespace EzDesk.Deploy
{
    internal class DeployPresenter
    {
        private Mainform _view;

        public DeployPresenter(Mainform mainform)
        {
            this._view = mainform;
        }
        string connStr = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=EzDeskInit.mdb";

        internal void DoInitData()
        {
            IEzDeskInitial ezInit = new EzDeskInitial();
            ezInit.AddInitializeModule(new EzDeskAttendanceInitial());
            ezInit.AddInitializeModule(new EzDeskMessageInitial());
            ezInit.AddInitializeModule(new EzDeskProjectInitial());
            ezInit.Initialize();

            MessageBox.Show("数据初始化成功！");
        }

        public bool TestDbConnection()
        {
            // 尝试连接sql server
            var canSqlConn = false;
            try
            {
                EzDeskDatabaseContainer.Go(
                    container =>
                        {
                            var test = Enumerable.ToList<UserProfile>(container.UserProfileSet);
                        });
                canSqlConn = true;
            }catch (Exception /*ex*/){}
            if (!canSqlConn)
            {
                MessageBox.Show(@"你得确保.\sqlexpress能正常使用，程序现在将退出");
                return false;
            }



            // 尝试连接mdb
            var canMdbConn = false;
            try
            {
                using (OdbcConnection conn = new OdbcConnection(connStr))
                {
                    conn.Open();

                    // 导入部门
                    string sqlStr = "SELECT * FROM dept ";
                    OdbcCommand cmd = new OdbcCommand(sqlStr, conn);
                    OdbcDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {

                    }
                }
                canMdbConn = true;
            }catch(Exception)
            {
                
            }
            if (!canMdbConn)
            {
                MessageBox.Show("你得确保EzDeskInit.mdb能正常使用，程序现在将退出");
                return false;
            }

            // 测试通过，哈哈
            return true;
        }

        public void refreshInitInfo()
        {
            dynamic initInfo = new ExpandoObject();
            using (OdbcConnection conn = new OdbcConnection(connStr))
            {
                conn.Open();

                string sqlStr = "SELECT * FROM company";
                OdbcCommand cmd = new OdbcCommand(sqlStr, conn);
                OdbcDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    initInfo.CompanyName = dr["name"] as string;
                    initInfo.ConpanyShortName = dr["s_name"] as string;
                    initInfo.ExpirDate = (DateTime)dr["exp"];
                }

                sqlStr = "SELECT * FROM userinf";
                cmd = new OdbcCommand(sqlStr, conn);
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    initInfo.AdminName = dr["username"] as string;
                }

                sqlStr = "SELECT COUNT(*) FROM dept";
                cmd = new OdbcCommand(sqlStr, conn);
                initInfo.DeptCount = cmd.ExecuteScalar();

                sqlStr = "SELECT COUNT(*) FROM userlevel";
                cmd = new OdbcCommand(sqlStr, conn);
                initInfo.PositionCount = cmd.ExecuteScalar();


                initInfo.CanInitData = true;

            }

            _view.displayInitInfo(initInfo);
        }

        internal void refreshExpirData()
        {
            dynamic expirData = new ExpandoObject();
            EzDeskDatabaseContainer.Go(
                container =>
                    {
                        var orgInfo = container.OrganizationSet.FirstOrDefault();
                        var expStr = orgInfo.Exp;
                        var dataStr = Des.DecryptDES(expStr, "weimargro");
                        var expDate = EpochDateTimeExtension.FromEpoch(Convert.ToInt64(dataStr.Substring(0, 10)));
                        expirData.ExpirDate = expDate;
                    });
            
            _view.displayExpirData(expirData);
        }

        public void SetExpirDate(DateTime selectDate)
        {
            var epochstr = selectDate.ToEpoch().ToString() + "weimar";


            EzDeskDatabaseContainer.GoAndSave(
                container =>
                    {
                        var orgInfo = container.OrganizationSet.FirstOrDefault();
                        var expStr = Des.EncryptDES(epochstr, "weimargr");
                        orgInfo.Exp = expStr;
                    });

        }
    }
}